<template>
  <div id="app">
    <fieldset>
      <p>
        <span>姓名：</span>
        <input type="text" name="username" class="username" v-model="data.student.username" />
      </p>
      <p>
        <span>年龄：</span>
        <input type="text" name="age" class="age" v-model="data.student.age" />
      </p>
      <p>
        <span>性别：</span>
        <select name="sex" id="sex" v-model="data.student.sex">
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </p>
      <p>
        <span>手机：</span>
        <input type="text" name="phone" class="phone" v-model="data.student.phone">
      </p>
      <button id="but" @click="add()">确认提交</button>
    </fieldset>

    <!-- 第二部分：信息展示 -->
    <table>
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>手机</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(student, index) in data.students" :key="index">
          <td>{{ student.username }}</td>
          <td>{{ student.age }}</td>
          <td>{{ student.sex }}</td>
          <td>{{ student.phone }}</td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { reactive } from 'vue'

const data = reactive({
  student: {
    username: '',
    age: '',
    sex: '男',
    phone: ''
  },
  students: []
})

const add = () => {
  if (data.student.username && data.student.age && data.student.phone) {
    data.students.push({...data.student})
    // 清空表单
    data.student.username = ''
    data.student.age = ''
    data.student.phone = ''
  }
}

const del = (index) => {
  data.students.splice(index, 1)
}
</script>


<style scoped>
 table,
        tr,
        th,
        td {
            border: 1px solid #ccc;
        }

        tr {
            height: 40px;
        }

        table {
            border-collapse: collapse;
            width: 630px;
            text-align: center;
            margin: 20px auto;
        }

        thead {
            background-color: yellowgreen;
        }

        fieldset {
            width: 600px;
            margin: 0 auto;
        }

        input {
            height: 20px;
        }
</style>